package cn.bocweb.spinning.util;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

/**
 * Created by chenchangxing on 15/11/11.
 */
public class DeviceUtil {

    public static final String LOG = "treature";

    public static final String REGEX_MOBILE = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";


    public static void Log(String content) {
        Log.e(LOG,content);
    }

    public static void MyToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    //dip 转 px
    public static int dip2px(Context context, double d)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (d * scale + 0.5f);
    }

    //px 转 dip
    public static int px2dip(Context context, float pxValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    //拿到屏幕宽度
    public static int getScreenWidth(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    //获取屏幕的高度
    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();

        return display.getHeight();
    }

    //获得版本号
    public static String GetSystemVersionName (Context context) {
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("versionCode", e.getMessage());
            return "";
        }
    }


    public static Date getDateFromMillis (long timeMilis) {
        return new Date(timeMilis * 1000);
    }

    public static Date getDateFromMillis1 (long timeMilis) {
        return new Date(timeMilis);
    }


    public static String format (Date date, String format) {
        String result = "";
        try {
            if (date != null) {
                DateFormat df = new SimpleDateFormat(format, Locale.getDefault());
                result = df.format(date);
            }
        } catch (Exception e) {}
        return result;
    }

    //获得倒计时时间 时分秒
    public static String getTickInfo(long timeSpacing) {
        if (timeSpacing < 0 || timeSpacing == 0) {
            return "";
        } else {
            long oneMin = 60;
            long oneHour = 60*60;
            long oneDay = oneHour*24;
            if (timeSpacing < oneMin) {
                int second = (int)timeSpacing;
                return (second + "秒");
            }
            if (timeSpacing > oneMin && timeSpacing < oneHour) {
                int min = (int)(timeSpacing/60);
                int second = (int)(timeSpacing - min * 60);
                return (min + "分" + second + "秒");
            }
            if (timeSpacing > oneHour) {
                int hour = (int)(timeSpacing/(60*60));
                int min = (int)((timeSpacing - hour * (60*60)) / 60);
                int second = (int)((timeSpacing - hour * (60*60)) - min * 60);
                return (hour + "小时" + min + "分" + second + "秒");
            }
        }
        return null;
    }



    public static String getTickInfoForData(long timeSpacing) {
        if (timeSpacing < 0 || timeSpacing == 0) {
            return "";
        } else {
            long oneMin = 60;
            long oneHour = 60*60;
            long oneDay = oneHour*24;
            if (timeSpacing < oneMin) {
                int second = (int)timeSpacing;
                if (second > 9) {
                    return ("00:" + second);
                } else {
                    return ("00:0" + second);
                }
            }
            if (timeSpacing >= oneMin && timeSpacing < oneHour) {
                int min = (int)(timeSpacing/60);
                String minStr;
                if (min > 9) {
                    minStr = String.valueOf(min);
                } else {
                    minStr = "0" + String.valueOf(min);
                }
                int second = (int)(timeSpacing - min * 60);
                String secStr;
                if (second > 9) {
                    secStr = String.valueOf(second);
                } else {
                    secStr = "0" + String.valueOf(second);
                }
                return (minStr + ":" + secStr);
            }
            if (timeSpacing >= oneHour) {
                int hour = (int)(timeSpacing/(60*60));
                int min = (int)((timeSpacing - hour * (60*60)) / 60);
                String minStr;
                if (min > 9) {
                    minStr = String.valueOf(min);
                } else {
                    minStr = "0" + String.valueOf(min);
                }
                int second = (int)((timeSpacing - hour * (60*60)) - min * 60);
                String secStr;
                if (second > 9) {
                    secStr = String.valueOf(second);
                } else {
                    secStr = "0" + String.valueOf(second);
                }
                return (hour + ":" + minStr + ":" + secStr);
            }
        }
        return null;
    }

    //获得离现在的时间 时分秒
    public static String getTimeByTwoTimeStamp(long earlyTime, long laterTime){
        if (laterTime < earlyTime) {
            return "0秒前";
        }else {
            long timeSpacing = (laterTime - earlyTime)/1000;
            long oneMin = 60;
            long oneHour = 60*60;
            long oneDay = oneHour*24;
            if (timeSpacing < oneMin) {
                int time = (int) timeSpacing;
                return (time + "秒前");
            }
            if (timeSpacing > oneMin && timeSpacing < oneHour) {
                int time = (int)(timeSpacing/60);
                return (time + "分钟前");
            }
            if (timeSpacing > oneHour && timeSpacing < oneDay) {
                int time = (int)(timeSpacing/(60*60));
                return (time + "小时前");
            }
            if (timeSpacing > oneDay) {
                Date date = getDateFromMillis(earlyTime);
                String dateString = format(date, "yyyy-MM-dd HH:mm");
                return dateString;
            }
        }

        return "";
    }

    public static String getTimeForDate(long earlyTime, long laterTime) {
        Date date = getDateFromMillis(earlyTime / 1000);
        String dateString = format(date, "yyyy-MM-dd");
        return dateString;
    }


    //获得离现在的时间 时分秒
    public static String getTimeByTwoTimeStampForPhp(long earlyTime, long laterTime){
        if (laterTime < earlyTime) {
            return "0秒前";
        }else {
            long timeSpacing = (laterTime - earlyTime)/1000;
            long oneMin = 60;
            long oneHour = 60*60;
            long oneDay = oneHour*24;
            if (timeSpacing < oneMin) {
                int time = (int) timeSpacing;
                return (time + "秒前");
            }
            if (timeSpacing > oneMin && timeSpacing < oneHour) {
                int time = (int)(timeSpacing/60);
                return (time + "分钟前");
            }
            if (timeSpacing > oneHour && timeSpacing < oneDay) {
                int time = (int)(timeSpacing/(60*60));
                return (time + "小时前");
            }
            if (timeSpacing > oneDay) {
                Date date = getDateFromMillis(earlyTime / 1000);
                String dateString = format(date, "yyyy-MM-dd HH:mm");
                return dateString;
            }
        }

        return "";
    }
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;

        Object obj = null;

        Field field = null;

        int x = 0, sbar = 0;

        try {

            c = Class.forName("com.android.internal.R$dimen");

            obj = c.newInstance();

            field = c.getField("status_bar_height");

            x = Integer.parseInt(field.get(obj).toString());

            sbar = context.getResources().getDimensionPixelSize(x);

        } catch (Exception e1) {

            e1.printStackTrace();

        }

        return sbar;
    }

    public static String getIp(Context context){
        WifiManager wm=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        //检查Wifi状态
        if(!wm.isWifiEnabled())
            wm.setWifiEnabled(true);
        WifiInfo wi=wm.getConnectionInfo();
        //获取32位整型IP地址
        int ipAdd=wi.getIpAddress();
        //把整型地址转换成“*.*.*.*”地址
        String ip=intToIp(ipAdd);
        return ip;
    }

    private static String intToIp(int i) {
        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }

    /**
     * 校验手机号
     *
     * @param mobile
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isMobile(String mobile) {
        return Pattern.matches(REGEX_MOBILE, mobile);
    }

    //验证邮政编码
    public static boolean isCode(String post){
        if(post.matches("[1-9]\\d{5}(?!\\d)")){
            return true;
        }else{
            return false;
        }
    }

    public static String getTime (Date date) {
        return format(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getHHMMSS (Date date) {
        return format(date, "mm:ss");
    }

    public static String getDateTime (Date date) {
        return format(date, "yyyy-MM-dd");
    }

    public static byte[] bitmap2Bytes(Bitmap bitmap) {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, b);
        return  b.toByteArray();
    }

    public static String bytes2String(byte[] b) {
        try {
            return new String(b, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getImageAbsolutePath(Activity context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[] { split[1] };
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = { column };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static String encodeBase64File(String path) throws Exception {
        BitmapDrawable bd = (BitmapDrawable) BitmapDrawable.createFromPath(path);
        Bitmap bitmap = bd.getBitmap();
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, b);
        byte[] bytes = b.toByteArray();
        bd.getBitmap().recycle();

        return Base64.encodeToString(bytes, 0, bytes.length, Base64.DEFAULT);
    }

    public static int getViewHeight(View view) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);

        int toolbarHeight = view.getMeasuredHeight();
        return toolbarHeight;
    }

    public static String getMD5(String message)
    {
        String md5str = "";
        try
        {
            // 创建一个提供信息摘要算法的对象，初始化为md5算法对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 将消息变成byte数组
            byte[] input = message.getBytes();
            // 计算后获得字节数组,这就是那128位了
            byte[] buff = md.digest(input);
            // 把数组每一字节（一个字节占八位）换成16进制连成md5字符串
            md5str = bytesToHex(buff);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return md5str;
    }

    /**
     * 二进制转十六进制
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes)
    {
        StringBuffer md5str = new StringBuffer();
        // 把数组每一字节换成16进制连成md5字符串
        int digital;
        for (int i = 0; i < bytes.length; i++)
        {
            digital = bytes[i];
            if (digital < 0)
            {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }


        return md5str.toString();
    }

    public static String getSign(String timelime) {

        return getMD5(timelime + "fzbocweb");
    }

    public static String getBase64(String pwd) {
        return Base64.encodeToString((pwd + "fzapp").getBytes(), Base64.DEFAULT);
    }

    public static String getVidBase64(String str) {
        return Base64.encodeToString((str).getBytes(), Base64.DEFAULT);
    }

    public static File saveFile(Bitmap bm, String fileName, Context context) {
            try {
                String path = context.getCacheDir().getPath() + fileName;
                File dirFile = new File(path);
                if(!dirFile.exists()){
                    dirFile.mkdir();
                }
                File file = new File(path);
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                if (bm.compress(Bitmap.CompressFormat.JPEG, 80, bos)) {
                    bos.flush();
                    bos.close();
                }
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
        return null;
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }
}
